package com.jvyou.thread.test06;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @author 橘柚
 * @version 1.0-SNAPSHOT
 * @Date 2024/7/31 16:38
 * @Description 抽奖
 */
public class Lottery implements Callable<Integer> {
    // 奖池
    private final int[] numbers;
    // 剩余的奖品数量
    private int count;

    Lottery(int[] numbers) {
        this.numbers = numbers;
        this.count = numbers.length;
    }

    @Override
    public Integer call() throws Exception {
        String name = Thread.currentThread().getName();
        List<Integer> list = new ArrayList<>();
        while (true) {
            synchronized (this) {
                if (count <= 0) {
                    System.out.println(name + ">>" + list);
                    break;
                } else {
                    int index = (int) (Math.random() * numbers.length);
                    if (numbers[index] != 0) {
                        // 将抽奖结果保存起来
                        list.add(numbers[index]);
                        numbers[index] = 0;
                        count--;
                    }
                }
            }
            Thread.sleep(100);
        }

        return Collections.max(list);
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        int[] numbers = {10, 5, 20, 50, 100, 200, 500, 800, 2, 80, 300, 700};
        Lottery lottery = new Lottery(numbers);

        FutureTask<Integer> task1 = new FutureTask<>(lottery);
        FutureTask<Integer> task2 = new FutureTask<>(lottery);

        Thread t1 = new Thread(task1, "抽奖1");
        Thread t2 = new Thread(task2, "抽奖2");

        t1.start();
        t2.start();

        System.out.println("最大值" + Math.max(task1.get(), task2.get()));
    }
}
